package org.xu.logic;

import cn.hutool.poi.excel.ExcelReader;
import com.core.exception.BzException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.xu.bo.ExcelBO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class SQLGenerateUpdateLogicImpl implements SQLGenerateUpdateLogic {

    private String tableName = "sg_vehicle_info";

    @Override
    public void generateUpdateSQL(MultipartFile file) {
        List<String> sqlList = new ArrayList<>();
        HashMap<String, Integer> map = new HashMap<>();
        List<ExcelBO> list = generate(file);
        for (ExcelBO excelBO : list) {
            String sql = "UPDATE table SET 参1数 WHERE 条1件 ;";
            sql = sql.replaceAll("table",tableName);
            sql = sql.replaceAll("参1数",getValues(excelBO));
            String condition = getCondition(excelBO);
            sql = sql.replaceAll("条1件",condition);
           // sqlList.add(sql);
            System.out.println(sql);
            Integer count = map.get(condition) == null ? 0 : map.get(condition);
            map.put(condition,++count);
        }
        System.out.println("---------");
        System.out.println("生成条数:"+ list.size());
        map.forEach((c,count) ->{
            if (count > 1){
                System.out.println("重复的条件:"+ c + count);
            }
        });
    }
//  UPDATE `sg_garage_info` SET longitude = xx,latitud = xx WHERE garage_name = '';
    private String getValues(ExcelBO excelBO){

        return "str";
    }

    private String getCondition(ExcelBO excelBO){
        return "str";
    }

    private List<ExcelBO> generate(MultipartFile file){
        try {
            // 存储 处理的excel
            List<ExcelBO> excelList;
            ExcelReader reader = new ExcelReader(WorkbookFactory.create(file.getInputStream()), 0);
            reader.setHeaderAlias(ExcelBO.HEADER_ALIAS);
            excelList = reader.read(0, 0, ExcelBO.class);
            if (CollectionUtils.isEmpty(excelList)) {
                throw new BzException("excel数据为空,导入失败");
            }
            return excelList;
        }catch (BzException e){
            throw e;
        }catch (Exception e) {
            log.info("解析 excel异常，", e);
            throw new BzException("解析 excel异常");
        }
    }
}
